﻿using UnityEngine;
using System.Collections;

public class player : MonoBehaviour {
	Vector3 playerNext;
	Vector3 change;
	Vector3 DirectEuler;
	Vector3 Direct;
	float next=0;
	public float delay; 

	void Detection(Vector3 direct){
		RaycastHit hit;
		if (Physics.Raycast (this.gameObject.transform.position, direct, out hit, 1)) {
			if(hit.transform.tag=="box"){
				RaycastHit boxhit;
				if(Physics.Raycast(hit.transform.position,direct,out boxhit,1))
				{
					if(boxhit.transform.tag!="goods"){
						change =new Vector3(0,0,0);
					}else{
						change= direct;
					}
				}
				else{
					change=direct;
				}
				hit.transform.position=hit.transform.position+change;
			}
			else if(hit.transform.tag=="wall"){
				change=new Vector3(0,0,0);
			}else{
				change=direct;
			}
		}
		else{
			change=direct;
		}
	}
	void move(){
		playerNext=this.gameObject.transform.position+change;
		iTween.MoveTo(this.gameObject,playerNext,0.5f);
		iTween.RotateTo(this.gameObject,DirectEuler,0.2f);
	}

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if (Gamemanager.gamesSTR == true) {
		
			if (Input.GetKey (KeyCode.W) && Time.time > next) {
				next = delay + Time.time;
				DirectEuler = new Vector3 (0, 180, 0);
				Direct = Vector3.right;
				Detection (Direct);
				move ();
			}
		
		
		
			if (Input.GetKey (KeyCode.S) && Time.time > next) {
				next = delay + Time.time;
				DirectEuler = new Vector3 (0, 0, 0);
				Direct = Vector3.left;
				Detection (Direct);
				move ();
			}
		
		
			if (Input.GetKey (KeyCode.A) && Time.time > next) {
				next = delay + Time.time;
				DirectEuler = new Vector3 (0, 90, 0);
				Direct = Vector3.forward;
				Detection (Direct);
				move ();
			}
		
		
			if (Input.GetKey (KeyCode.D) && Time.time > next) {
				next = delay + Time.time;
				DirectEuler = new Vector3 (0, -90, 0);
				Direct = Vector3.back;
				Detection (Direct);
				move ();
			}
		} 
	}

	}
